package cn.zbzcode.mq._02work_queues;

import cn.zbzcode.mq.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Rev2 {
    public static void main(String[] args) {
        try {
            //1.通过工具,创建连接
            Connection connection = ConnectionUtil.getConnection();

            //2.通过连接创建通道
            final Channel channel = connection.createChannel();

            //3.通过通道申明队列:从哪个队列取消息
            channel.queueDeclare(Sen.WORK_QUEUES,true,false,false,null);

            //4.通过通道接收消息

            //一个消费者同时处理一个消息
            channel.basicQos(1);

            Consumer callback = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                                           AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //int i = 1 / 0;
                    System.out.println("消费者ID:consumerTag:"+consumerTag);
                    System.out.println("交换机:Exchange:"+envelope.getExchange());
                    System.out.println("队列名:RoutingKey:"+envelope.getRoutingKey());
                    System.out.println("消息ID:DeliveryTag:"+envelope.getDeliveryTag());
                    System.out.println("MessageId:"+properties.getMessageId());
                    System.out.println("消息内容:"+new String(body));

                    //触发手动签收
                    //参数: 消息ID ,确认所有消息
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            };
            //参数: 队列名 , 签收方式 ,回调方法
            channel.basicConsume(Sen.WORK_QUEUES, false, callback);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}